import React, { useState,ChangeEvent, useEffect ,useLayoutEffect} from 'react';
import { Form, Input, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete, InputNumber } from 'antd';
import { getProlabel, getProTradeList,addProTable,upLoadImg} from '@/services/modules/pro';
import { RootObject, RootObject2, RootObject3 } from '@/utils';
import { observer } from 'mobx-react-lite';
import useStore from '@/context/useStore';
import Editor from 'for-editor';
import {Link,IRouteComponentProps} from 'umi';
import { Collapse ,Modal} from 'antd';
import { Upload, message} from 'antd';
import { UploadOutlined } from '@ant-design/icons';


import './addProject.less';
import { Tabs } from 'antd';

const { TabPane } = Tabs;
const { Option } = Select;
const { Panel } = Collapse;

const tables = ['任务名称','任务成果','保薪技能','提薪技能','考核标准','步骤数量','推荐工期','操作'];

// {name:'',version:'',description:'',stationName:'',tradeName:'',sxType:0,subjectTime:0}
// 上传
const props = {
    name: 'file',
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info:any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};
const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 16,
            offset: 8,
        },
    },
};


interface Inputs{
    name:string,
    address:string,
    mes:string,
    id:number
}


const AddProject: React.FC<IRouteComponentProps> = ({history,location}) => {
    
    // 获取行业
    const [MajorList, SetMajorList] = useState<RootObject[]>([]);
    const [TradeList, SetTradeList] = useState<RootObject2[]>([]);
    const [fileImg,setFileImg] = useState('');          // 上传图片
    const {proXm} = useStore();                         // 仓库
    const [form] = Form.useForm();
    const [formValues,setFormValues] = useState({});
    const [autoCompleteResult, setAutoCompleteResult] = useState<string[]>([]);
    const websiteOptions = autoCompleteResult.map(website => ({
        label: website,
        value: website,
    }));

    // 实训管理数据
    const [inputThree,setInputThree] = useState<Inputs[]>([{name:'',address:'',mes:'',id:Date.now()}]); 
    // 前置项目
    const [Leadproject,setLeadproject] = useState([{id:Date.now()}]);

    // 上传文件
    const [isModalVisible, setIsModalVisible] = useState(false);
    const showModal = () => {
      setIsModalVisible(true);
    };
    const handleOk = () => {
      setIsModalVisible(false);
    };
    const handleCancel = () => {
      setIsModalVisible(false);
    };


    let detailId = location.query.versionId;
    // 获取详情
    // useEffect(()=>{
        
        
    // },[])
    


    // 获取表单数据
    const onFinish = ({...values}) => {
        console.log('Received values of form: ', values);
        let arr = ['生成实训','教学实训','专业群'];
        let cid= arr.findIndex(item=>item == values.sxType);
        // console.log(cid,'下标aaaaa')
        alert('添加成功！')
        setFormValues({...values,sxType:cid,pictureUrl:fileImg})
    };
    useEffect(()=>{
        addProTable(formValues)
    },[formValues])


    // 上传图片
    async function uploadImage(e:any){
        let form = new FormData();
        let files = e.target.files;
        // console.log(files[0],'上传');
        form.append("file",files[0]);
        let result = await upLoadImg(form as any);
        if(result.code === 200){
            setFileImg(result.url)
        }
        // console.log(result,'结果')
    }

    // 获取行业接口
    useEffect(() => {
        if(detailId){
            proXm.getProDetail(detailId);
        }
        console.log('定位id',detailId)


        // 专业
        getProlabel().then((res:any) => {
            if (res.code === 200) {
                SetMajorList(res.data);
            }
        });
        // 行业
        getProTradeList().then((res:any) => {
            if (res.code === 200) {
                SetTradeList(res.data);
            }
        })
        // 实训大纲
        proXm.getProBriefTree();
        // 项目资源
        proXm.getResourceTree();
        // 前置项目
        proXm.getPushProList();

        
    },[])


    // tabel切换
    function callback(key: any) {
        console.log(key);
    }
    // 添加实训管理
    function addInputThres(){
        let input = [...inputThree, {name:'',address:'',mes:'',id:Date.now()}]
        setInputThree(input);
    }
    // 减少实训管理
    function reduceInputThree(id:number){
        let input = inputThree.filter(item=>item.id != id);
        setInputThree(input);
    }
    function changeInputs(e:ChangeEvent,index:number){
        let str = (e.target as HTMLInputElement).name;
        if(str == 'name'){
            inputThree[index].name = (e.target as HTMLInputElement).value;
        }else if(str == 'address'){
            inputThree[index].address = (e.target as HTMLInputElement).value;
        }else if(str == 'mes'){
            inputThree[index].mes = (e.target as HTMLInputElement).value;
        }
        let input = [...inputThree];
        setInputThree(input);
    }
    
    // 前置项目
    function onChange(value:any){
        console.log(value);
    }
    // console.log('加油啊详情页。。。。。。',{...proXm.proDetails})
    console.log('实训大纲',proXm.proBriefTree)
    return <div className='addProject'>
        
        <div className="header">
            <div>项目 / 添加项目</div>
        </div>
        <div className="main">
            <div className="main_head">
                <h3>添加项目</h3>
                <div>
                    <Link to='/teachers/proManagement/proManagement' onClick={()=>{proXm.clearDetail()}}>返回</Link>
                    <Button type="primary">提交审核</Button>
                </div>
            </div>
            <div className="main_hot">
                <h3>基本信息</h3>
                <Button>保存</Button>
            </div>
            <div className="main_center">
                
                <Form
                    {...formItemLayout}
                    form={form}
                    name="register"
                    onFinish={onFinish}
                    scrollToFirstError
                    key={JSON.stringify(proXm.proDetails)}
                    initialValues={ proXm.proDetails && {...proXm.proDetails}}
                >
                    
                    {/* 左边 */}
                    <Form.Item className='main_center_left'>
                        <Form.Item
                            label="项目名称"
                            name='name'
                            rules={[{ required: true, message: '请输入项目名称' }]}
                            style={{ width: '490px', height: '40px' }}
                        >
                            <Input placeholder='请输入项目名称' />
                        </Form.Item>

                        <Form.Item label='版本 V'
                            name='version'
                            style={{ width: '150px' }}
                            rules={[{ required: true, message: '请输入项目名称' }]}>
                            <Input />
                        </Form.Item>

                        <Form.Item className='el-form-item' name='description'>
                            <Input placeholder='请输入项目简介' style={{ width: "650px", height: "55px", margin: '0 30px' }} />
                        </Form.Item>

                        <Form.Item
                            name='majorStationList'
                            label="专业"
                            rules={[{ type: 'array', required: true, message: '请选择专业' }]}
                            style={{ width: "280px", height: '40px' }}
                        >
                            <Cascader options={MajorList} style={{ width: "204px" }} />
                        </Form.Item>

                        <Form.Item
                            label="行业"
                            name='trade'
                            rules={[{ required: true, message: '请选择行业' }]}
                            style={{ width: "350px", height: '40px' }}
                        >
                            <Cascader options={TradeList} style={{ width: '250px' }} />
                        </Form.Item>

                        <Form.Item
                            label="实训类型"
                            name='sxType'
                            rules={[{ required: true, message: '请选择实训类型' }]}
                            style={{ width: "280px", height: '36px' }}
                        >
                            <Select placeholder="选择类型" >
                                <Option value="生成实训">生产实训</Option>
                                <Option value="教学实训">教学实训</Option>
                                <Option value="专业群">专业群</Option>
                                
                            </Select>
                        </Form.Item>

                        <Form.Item 
                            label="预期总工时" 
                            name='subjectTime'
                            rules={[{ required: true, message: '请选择实训类型' }]}
                            style={{ width: "205px", fontSize: '16px', fontWeight: 'bold' }}>
                            <Form.Item noStyle name='subjectTime'>
                                <InputNumber min={1} max={10} style={{ width: '70px' }} />
                            </Form.Item>
                            <span className="ant-form-text">天</span>
                        </Form.Item>

                        <Form.Item className='el-form-item' style={{ fontSize: '16px' }}>
                            <b>技能点：</b>
                            <span style={{ color: '#ccc' }}>技能点由任务知识点内容生成</span>
                        </Form.Item>

                    </Form.Item>
                    {/* 右边 */}
                    <Form.Item className='main_center_right'>
                        <Form.Item                        
                            label="封面"
                            name='pictureUrl'
                            style={{ width: '350px' }}
                            rules={[{ required: true, message: '请上传封面' }]}
                        >
                            <div style={{ width: '260px', height: '152px', border: 'solid 1px #ccc', textAlign: 'center', lineHeight: '150px' }}>
                                {
                                    fileImg || (proXm.proDetails.pictureUrl && location.query.versionId) ? <img src={'http://111.203.59.61:8060'+(fileImg || proXm.proDetails.pictureUrl)} style={{width:'100%',height:'100%'}} />
                                    : <div>
                                        <span>+</span>
                                        <span onClick={showModal}>
                                            上传封面
                                        </span>
                                    </div>
                                }
                                <Modal title="Basic Modal" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                                    <input type="file" onChange={e=>{uploadImage(e)}} />
                                </Modal>
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="演示地址"
                            name='showUrl'
                            rules={[{ required: true, message: '请输入演示地址' }]}
                            style={{ width: "350px" }}
                        >
                            <Input placeholder='请输入演示地址' />
                        </Form.Item>

                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">
                                保存
                            </Button>
                        </Form.Item>
                    </Form.Item>


                </Form>
            </div>
        </div>
        <div className="footer">
                <Tabs defaultActiveKey="1" onChange={callback} size='large'>
                    <TabPane tab="实训大纲" key="1">
                      
                        <Collapse accordion>
                            {
                                proXm.proBriefTree && proXm.proBriefTree.map((item,index)=>{
                                    return <Panel header={item.label} key={index}>
                                        {
                                            item.children && item.children.map((el,le)=>{
                                                return <li key={le}>
                                                    {el.label}
                                                </li>
                                            })
                                        }
                                    </Panel>
                                })
                            }
                        </Collapse>
                        <Editor></Editor>
                    </TabPane>
                    <TabPane tab="实训任务" key="2">
                        <div className='tables'>
                            <div className="tables_head">
                                <span></span>
                                <Button type='primary'>添加任务</Button>
                            </div>
                            <div className="tables_center">
                                {
                                    tables.map((item,index)=>{
                                        return <span key={index}>
                                            {item}
                                        </span>
                                    })
                                }
                            </div>
                            <div className="tables_img">
                                <img src="http://111.203.59.61:8060/static/img/Lock.0318bb9d.svg" alt="" />
                                <p>
                                    还没有任务信息，点击 <a href="#">添加任务</a> 去创建新的任务吧
                                </p>
                            </div>
                        </div>
                    </TabPane>
                    <TabPane tab="项目资源" key="3">
                        <Collapse accordion>
                            {
                                proXm.proResourceTree && proXm.proResourceTree.map((item,index)=>{
                                    return <Panel header={item.label} key={index}>
                                        {
                                            item.children.map((el,le)=>{
                                                return <li key={le}>
                                                    {el.label}
                                                </li>
                                            })
                                        }
                                    </Panel>
                                })
                            }
                        </Collapse>
                        <Editor></Editor>
                    </TabPane>
                    <TabPane tab="实训环境" key="4">
                        <div className="tables4">
                        {
                             inputThree.map((item,index)=>{
                                return <div key={index}>
                                    <p>
                                        <span>环境名称</span>
                                        <input type="text" name='name' value={item.name} onChange={(e)=>{changeInputs(e,index)}} />
                                        <button onClick={()=>addInputThres()}>+</button>
                                        <button onClick={()=>reduceInputThree(item.id)}>-</button>
                                    </p>
                                    <p>
                                        <span>环境地址</span>
                                        <input type="text" name='address' value={item.address} onChange={(e)=>{changeInputs(e,index)}} />
                                    </p>
                                    <p>
                                        <span>环境描述</span>
                                        <input type="text" name='mes' value={item.mes} onChange={(e)=>{changeInputs(e,index)}} />
                                    </p>
                                </div>
                            })
                        }
                        </div>
                    </TabPane>
                    <TabPane tab="前置项目" key="5">
                        <div className='lades'>
                            <div className='lades_head'>
                                <span></span>
                                <Button type='primary'>保存</Button>
                            </div>
                            <div className='lades_center'>
                                <p>添加与新项目关联的项目</p>
                                {
                                    Leadproject.map((item,index)=>{
                                        return <div key={item.id}>
                                            <Cascader
                                                options={proXm.proPushProList}
                                                onChange={onChange}
                                            />
                                            <span className='spans' onClick={()=>{
                                                let inputs = [...Leadproject,{id:Date.now()}]
                                                setLeadproject(inputs)
                                            }}>+</span>
                                            <span className='spans' onClick={()=>{
                                                let inputs = Leadproject.filter(el=>el.id != item.id)
                                                setLeadproject(inputs);
                                            }}>-</span>
                                        </div>
                                    })
                                }
                                
                            </div>
                        </div>
                        
                    </TabPane>
                </Tabs>
        </div>
    </div>
}

export default observer(AddProject);